# '''
# 导入图片窗口
# '''
#
import sys
import traceback
from functools import partial

import cv2
import numpy
import numpy as np
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel
from PyQt5.QtCore import Qt, QRectF, QPointF, QLineF
from PyQt5.QtGui import QPainter, QPixmap, QImage, QPen, QColor, QFont, QCursor

import yaml
#
# # def numpy_array_to_qpixmap(numpy_array):
# #     """
# #     将NumPy数组转换为QPixmap。
# #     参数:
# #     numpy_array: 包含图像数据的NumPy数组，格式通常是BGR或RGB。
# #     """
# #     try:
# #         # 确保NumPy数组的数据类型为uint8，这是QImage要求的
# #         assert numpy_array.dtype == np.uint8
# #
# #         # 根据图像的通道数决定QImage的格式
# #         if numpy_array.shape[2] == 3:  # RGB图像
# #             qimage_format = QImage.Format_RGB888
# #         elif numpy_array.shape[2] == 4:  # RGBA图像
# #             qimage_format = QImage.Format_RGBA8888
# #         else:
# #             raise ValueError("Unsupported number of channels")
# #
# #         # 需要注意的是，OpenCV读取的图像默认是BGR顺序，而QImage期望的是RGB，
# #         # 因此如果是BGR图像，需要进行通道转换
# #         if numpy_array.shape[2] == 3:  # BGR转RGB
# #             numpy_array = numpy_array[:, :, ::-1]
# #
# #         # 创建QImage对象
# #         height, width, channel = numpy_array.shape
# #         bytes_per_line = 3 * width  # 对于RGB图像，每行的字节数
# #         if channel == 4:  # 对于RGBA图像
# #             bytes_per_line = 4 * width
# #         image = QImage(numpy_array.data, width, height, bytes_per_line, qimage_format)
# #         image = image.rgbSwapped()  # 如果是从BGR转过来的，这里可以交换回RGB（如果需要的话）
# #
# #         # 从QImage创建QPixmap
# #         pixmap = QPixmap.fromImage(image)
# #     except:
# #         print(traceback.format_exc())
# #     return pixmap
#
# def array2pix(image, ismask=False):
#     if len(image.shape) == 2:
#         image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGRA)
#
#     if image.shape[2] == 1:
#         image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGRA)
#
#     if image.shape[2] == 3:
#         #image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
#         image = cv2.cvtColor(image, cv2.COLOR_BGR2BGRA)
#     #show1 = cv2.resize(image, (640, 480))
#     if ismask:
#         #image[:,:,3] = image[:,:,2]
#         pass
#
#     show1 = image
#     #QtImg = QImage(show1.data, show1.shape[1], show1.shape[0], QImage.Format_BGR888)
#     QtImg = QImage(
#         show1.data, show1.shape[1], show1.shape[0], QImage.Format_ARGB32)
#     pixmap = QPixmap(QtImg)
#     return pixmap
#
# def read_yaml(file_path):
#     with open(file_path, 'r') as file:
#         config = yaml.safe_load(file)
#     return config
#
#
# def write_yaml(data, file_path):
#     with open(file_path, 'w') as file:
#         yaml.safe_dump(data, file)
# class ImportImage(QWidget):
#     def __init__(self, imagePath):
#         super().__init__()
#         self.imagePath = imagePath
#         if isinstance(self.imagePath, str):
#             self.imagePath = cv2.imread(self.imagePath)
#         self.pixmap = array2pix(self.imagePath)
#
#         self.scale = 0.2
#         self.pixmap = self.pixmap.scaled(int(self.pixmap.width()*self.scale), int(self.pixmap.height()*self.scale), Qt.KeepAspectRatio, Qt.SmoothTransformation)
#
#
#
#         self.initUI()
#
#     def initUI(self):
#         # self.layout = QVBoxLayout(self)
#         # self.label = QLabel("双击图片加载，拖动矩形框的角来调整大小", self)
#         # self.layout.addWidget(self.label)
#         self.setWindowTitle('导入图片再检测')
#         self.resize(self.pixmap.width(), self.pixmap.height())  # 调整窗口大小以适应图片
#         pass
#
#     def paintEvent(self, event):
#         painter = QPainter(self)
#         painter.drawPixmap(0, 0, self.pixmap)
#
#
# if __name__ == "__main__":
#     app = QApplication(sys.argv)
#     widget = ImportImage(r"D:\data\save\fuba_tianxian\20240603\service1ng\step1_20240603_142024_077\img_1_20240603_142030_520_step1_NG_img.jpg")  # 替换为初始图片路径
#     widget.resize(widget.pixmap.width(), widget.pixmap.height())  # 调整窗口大小以适应图片
#     widget.show()
#     sys.exit(app.exec_())


from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QVBoxLayout, QHBoxLayout
from PyQt5.QtGui import QPixmap
import sys

from test_seg_kakou import get_algo_fubatianxian

def array2pix(image, ismask=False):
    if len(image.shape) == 2:
        image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGRA)

    if image.shape[2] == 1:
        image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGRA)

    if image.shape[2] == 3:
        #image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        image = cv2.cvtColor(image, cv2.COLOR_BGR2BGRA)
    #show1 = cv2.resize(image, (640, 480))
    if ismask:
        #image[:,:,3] = image[:,:,2]
        pass

    show1 = image
    #QtImg = QImage(show1.data, show1.shape[1], show1.shape[0], QImage.Format_BGR888)
    QtImg = QImage(
        show1.data, show1.shape[1], show1.shape[0], QImage.Format_ARGB32)
    pixmap = QPixmap(QtImg)
    return pixmap

class ImageAndButtons(QWidget):

    def __init__(self, img_path='', main_ui_handle=None):
        super().__init__()
        self.main_ui_handle = main_ui_handle
        self.img_path = img_path
        self.initUI()

    def center(self):
        qr = self.frameGeometry()
        cp = QApplication.desktop().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
    def initUI(self):
        # 创建一个用于显示图片的QLabel
        self.image_label = QLabel(self)
        self.pixmap = QPixmap(self.img_path)  # 替换为你的图片路径
        self.scale = 0.2
        self.pixmap = self.pixmap.scaled(int(self.pixmap.width() * self.scale), int(self.pixmap.height() * self.scale),
                                         Qt.KeepAspectRatio, Qt.SmoothTransformation)

        self.image_label.setPixmap(self.pixmap)

        # 创建5个按钮
        self.button1 = QPushButton('步骤1检测', self)
        self.button2 = QPushButton('步骤2检测', self)
        self.button3 = QPushButton('步骤3检测', self)
        self.button4 = QPushButton('步骤4检测', self)
        self.button5 = QPushButton('步骤5检测', self)

        self.button1.clicked.connect(partial(self.detect_again_slot, 1))
        self.button2.clicked.connect(partial(self.detect_again_slot, 2))
        self.button3.clicked.connect(partial(self.detect_again_slot, 3))
        self.button4.clicked.connect(partial(self.detect_again_slot, 4))
        self.button5.clicked.connect(partial(self.detect_again_slot, 5))


        # 使用QHBoxLayout来布局按钮
        self.button_layout = QHBoxLayout()
        self.button_layout.addWidget(self.button1)
        self.button_layout.addWidget(self.button2)
        self.button_layout.addWidget(self.button3)
        self.button_layout.addWidget(self.button4)
        self.button_layout.addWidget(self.button5)

        # 使用QVBoxLayout来布局图片和按钮
        self.main_layout = QVBoxLayout()
        self.main_layout.addWidget(self.image_label)
        self.main_layout.addLayout(self.button_layout)
        # main_layout.setStretch(0, 10)
        # self.main_layout.setStretch(1, 1)
        self.setLayout(self.main_layout)

        # self.setGeometry(300, 300, 600, 400)
        self.setWindowTitle('导入图片再检测')
        self.show()
        self.center()

    def detect_again_slot(self, step_mode):
        try:
            if self.main_ui_handle:
                detect_kakou_seg = self.main_ui_handle.ss.config['services']['service_1_dict']['algorithm_dict']['jc_handle']
            else:
                detect_kakou_seg = get_algo_fubatianxian()  # 算法
            img = cv2.imread(self.img_path)
            im1, out, end, ends, save_img = detect_kakou_seg(img,step_mode)
    
            # 画图
            # cv2.imwrite(fr'D:\data\240507fubatianxian\other\temp\{ind}_ret.jpg', im1) # 图片保存地址
            self.pixmap = array2pix(im1)
            self.scale = 0.2
            self.pixmap = self.pixmap.scaled(int(self.pixmap.width() * self.scale), int(self.pixmap.height() * self.scale),
                                             Qt.KeepAspectRatio, Qt.SmoothTransformation)
            self.image_label.setPixmap(self.pixmap)
        except:
            print(traceback.format_exc())

    # def mouseDoubleClickEvent(self, event): # 鼠标左键双击 20240625
    #     try:
    #         if event.button() == Qt.LeftButton:
    #             print("鼠标左键双击被检测到！")
    #             if self.cam_name == '步骤3.卡扣检测(装前)':
    #                 from ui.sub_ui.set_param_st3_class import ImageWithResizableBox
    #                 self.setParamWidget = ImageWithResizableBox(self.imgdrawer.image) # 交互式调整参数
    #                 self.setParamWidget.show()
    #             elif self.cam_name == '步骤5.卡扣检测(装后)':
    #                 from ui.sub_ui.set_param_st5_class import ImageWithResizableBox
    #                 self.setParamWidget = ImageWithResizableBox(self.imgdrawer.image) # 交互式调整参数
    #                 self.setParamWidget.show()
    #             elif self.cam_name == '步骤1.相机盖检测(装前)':
    #                 from ui.sub_ui.set_param_st1_class import ImageWithResizableBox
    #                 self.setParamWidget = ImageWithResizableBox(self.imgdrawer.image)  # 交互式调整参数
    #                 self.setParamWidget.show()
    #     except:
    #         print(traceback.format_exc())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    img_path = r"D:\data\save\fuba_tianxian\20240603\service1ng\step1_20240603_142024_077\img_1_20240603_142030_520_step1_NG_img.jpg"
    ex = ImageAndButtons(img_path)
    sys.exit(app.exec_())
